package com.gang.music.system.controller;

import com.gang.music.common.AjaxResult;
import com.gang.music.core.annotation.Before;
import com.gang.music.core.intercept.RequestValidator;
import com.gang.music.core.shiro.ShiroKit;
import com.gang.music.core.shiro.ShiroUser;
import com.gang.music.system.entity.User;
import com.smallchill.core.toolbox.captcha.Captcha;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 后台管理登录
 *
 */
@RequestMapping("/system/login")
@Controller
public class LoginAdminController extends BaseController {

	@Before(RequestValidator.class)
	@RequestMapping(method = RequestMethod.GET)
	public String systemLogin(HttpServletRequest request, HttpServletResponse response) {
		return "admin/login/admin_login";
	}
	
	@ResponseBody
	@RequestMapping(method = RequestMethod.POST)
	public AjaxResult login(User user, String imgCode, HttpServletRequest request,
			HttpServletResponse response) {
		
		if (!Captcha.validate(request, response, imgCode)) {
			return error("验证码错误");
		}
		
		Subject subject = ShiroKit.getSubject();
		UsernamePasswordToken token = 
				new UsernamePasswordToken(user.getLoginName(), user.getPlainPassword());
		try {
			subject.login(token);
			Session session = ShiroKit.getSession();
			ShiroUser shiroUser = (ShiroUser) subject.getPrincipal();
			session.setAttribute("shiroUser", shiroUser);
			return success();
		} catch (UnknownAccountException e) {
			e.printStackTrace();
			return error("账号或密码错误!");
		} catch (IncorrectCredentialsException e) {
			e.printStackTrace();
			return error("账号或密码错误!");
		}
	}
}
